package foundation.common.menu.composer;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedHashMap;
import java.util.Map;

import org.zkoss.util.logging.Log;
import org.zkoss.zk.ui.WebApp;
import org.zkoss.zk.ui.util.WebAppInit;

/**
 * @author hernan
 *
 */

public class SubMenuWebAppInit implements WebAppInit {
	private static final Log log = Log.lookup(SubMenuWebAppInit.class);
	
	final static String PATH = "";

	final static String CONFIG = "menu.properties";

	private static Map _subMenuMap = new LinkedHashMap () {
		 public Object remove(Object key) {
			 throw new UnsupportedOperationException();
		 }
		 public void clear() {
			 throw new UnsupportedOperationException();			 
		 }
	};
	
	public void init(WebApp wapp) throws Exception {
		loadProperites();
	}

	public static Map getSubMenuMap() {
		return _subMenuMap;
	}
	private void loadProperites() {
		try {
			BufferedReader bufReader = new BufferedReader(
					new InputStreamReader(this.getClass().getClassLoader().getResourceAsStream(CONFIG)));
			String prop = null;
			while ((prop = bufReader.readLine()) != null) {
				int begin = prop.indexOf("=");
				if (prop.startsWith("#") || prop.startsWith("!") || begin == -1)
					continue;
				
				final String key = prop.substring(0, begin).trim();
				final String values = prop.substring(begin + 1, prop.length()).trim();
				final String[] vals = values.split(",");
				if (vals.length == 0)
					continue;
					
					if (vals.length==2){
						//la funciones de chuqueo de seguridad esperan una lista separada por ",". 
						//en los .properties usamos ":" para no complicar el parser.
					
					SubMenu subMenu= new SubMenu(key,vals[0].trim(),vals[1].trim());
					_subMenuMap.put(subMenu.getId(),subMenu);
				}
			}
			bufReader.close();
		} catch (IOException e) {
			log.error("Ingored: failed to load a properties file, \nCause: "
					+ e.getMessage());
		}
	}
}
